package com.qipay.security.jwt;

import com.qipay.baas.model.Cp;
import com.qipay.cp.CpService;
import com.qipay.cp.config.CpAccountStateEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Date;


public class JWTUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    CpService cpService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        if (s == null) {
            throw new UsernameNotFoundException(String.format("No user found with username '%s'.", s));
        } else {
            Cp cp = cpService.getOneByAppId(s);
            if(cp == null) {
                throw new UsernameNotFoundException(String.format("No user found with username '%s'.", s));
            }

            if(CpAccountStateEnum.ENABLED.getState() != cp.getAccountState()) {
                throw new UsernameNotFoundException(String.format("'%s'已经被禁用.", s));
            }

            return new JWTUser(
                    cp.getId(),
                    cp.getAppId(),
                    passwordEncoder.encode(cp.getSecretId()),
                    new Date(1490788800000L),
                    cp.getSecretId()
            );
        }
    }
}
